<template>
  <div class="login-form px-6 py-8">
    <p class="text-base font-bold text-center pb-3">密码登录</p>
    <el-form :model="loginForm" :rules="loginFormRules" ref="formRef">
      <el-form-item prop="email">
        <el-input v-model="loginForm.email" placeholder="邮箱" size="large"></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="loginForm.password"
          placeholder="密码"
          size="large"
          type="password"
          show-password
          @keyup.enter.native="login"
        ></el-input>
      </el-form-item>
    </el-form>
    <div class="text-right text-sm">
      <span class="register-btn cursor-pointer" @click="toRegister">注册账号</span>
    </div>
    <div class="mt-3">
      <el-button class="w-full" type="primary" @click="login" :loading="loading">登录</el-button>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref } from 'vue'
import { ElForm, ElFormItem, ElInput, ElButton, FormRules, FormInstance } from 'element-plus'
import { trim } from 'lodash'
import { useRouter, useRoute } from 'vue-router'
import { loginAccount } from '@/services/ApiServer/signInRequest'
import { useUserStore } from '@/store/user'

export default defineComponent({
  name: 'loginForm',
  components: {
    ElForm,
    ElFormItem,
    ElInput,
    ElButton,
  },
  setup() {
    let loading = ref(false)
    const loginForm = reactive({
      email: '',
      password: '',
    })
    const validateEmail = (
      rule: any,
      value: string,
      callback: (error?: string | Error | undefined) => void
    ) => {
      if (trim(value) === '') {
        callback(new Error('请填写邮箱账号'))
      } else if (
        !/^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/.test(value)
      ) {
        callback(new Error('请输入正确的邮箱格式'))
      } else {
        callback()
      }
    }
    const loginFormRules = reactive<FormRules>({
      email: [{ trigger: 'blur', validator: validateEmail }],
      password: [{ required: true, message: '请填写密码', trigger: 'blur' }],
    })
    const router = useRouter()
    const route = useRoute()
    // 跳转注册页面
    const toRegister = () => {
      router.push('/signIn/register')
    }
    const formRef = ref<FormInstance | null>()
    const userStore = useUserStore()
    // 登录
    const login = () => {
      if (!formRef) return
      formRef.value?.validate(async (valid) => {
        if (valid) {
          loading.value = true
          const res = await loginAccount({
            email: loginForm.email,
            password: loginForm.password,
          })
          loading.value = false
          if (res && res.code === 0) {
            // 设置token
            userStore.setToken(res.data.token)
            // 获取用户信息
            userStore.getUserInfo()
            router.push((route.query.callbackUrl as string) || '/home')
          }
        }
      })
    }
    return {
      loginForm,
      loginFormRules,
      formRef,
      toRegister,
      login,
      loading,
    }
  },
})
</script>

<style lang="scss" scoped>
.login-form {
  width: 400px;
  background-color: #fff;
  margin: 0 auto;
  .register-btn {
    color: var(--text-primary);
    &:hover {
      color: #76839b;
      text-decoration: underline;
    }
  }
}
</style>
